<template>
	<div class="ele-body">
		<el-card shadow="never" v-loading="loading">
			<div class="_card">
				<div class="_form">
						<el-form ref="form"
					:rules="rules"
					:model="form"
					label-width="100px">
					<div class="form-title">作业打标</div>
					<el-form-item v-if="form.operation_no" label="作业编号：">
					<el-input v-model="form.operation_no" disabled></el-input>
					</el-form-item>
					<el-form-item label="作业类别：" prop="operation_category" required>
					<operation-category-select
						v-model="form.operation_category"
					></operation-category-select>
					</el-form-item>
					<el-form-item label="上报单位：" prop="organization_id" required>
					<organization-select :model_type="'emergency'"
						v-model="form.organization_id"
					></organization-select>
					</el-form-item>
					<el-form-item label="巡查分类：" prop="exception_category" required>
						<exception-category-select type="emergency" :unit="form.organization_id" v-model="form.exception_category"></exception-category-select>
					</el-form-item>
					<el-form-item label="打标地址：" prop="address" required>
					<el-cascader
						clearable
						v-model="form.area_id"
						class="ele-fluid"
						placeholder="请选择省市区"
						:options="regions"
						popper-class="ele-pop-wrap-higher"
						@change="changeArea"
					/>
					<el-input
						v-model="form.address"
						:readonly="form.address?false:true"
						placeholder="请在地图上选择详细地址"
					></el-input>
					<el-button size="mini" style="width: 100%; margin-top: 4px" @click="goHistory" v-if="form.operation_no">查看历史标记记录</el-button>
					<!-- <div @click="goHistory" class="logDiv" v-if="form.operation_no">查看历史标记记录</div> -->
					</el-form-item>
					<el-form-item label="单位可见：">
					<el-select
						clearable
						v-model="form.organization_show"
						placeholder="请选择单位是否可见"
						class="ele-fluid"
					>
						<el-option label="可见" :value="1" />
						<el-option label="不可见" :value="0" />
					</el-select>
					</el-form-item>
					<el-form-item label="是否处罚：" v-if="form.operation_category!==2">
					<el-select
						clearable
						v-model="form.penalty"
						placeholder="请选择是否处罚"
						class="ele-fluid"
					>
						<el-option label="是" :value="1" />
						<el-option label="否" :value="0" />
					</el-select>
					</el-form-item>
					<el-form-item label="备注:">
					<el-input
						:rows="3"
						clearable
						type="textarea"
						:maxlength="200"
						v-model="form.description"
						placeholder="备注"
					/>
					</el-form-item>
					<el-form-item label="异常图片:">
					<upload-image :limit="3" v-model="form.images"></upload-image>
					</el-form-item>
					<el-form-item>
					<el-button :loading="saveLoading" type="primary" @click="save">{{
						form.id ? '保 存' : '立即创建'
					}}</el-button>
					<el-button @click="$router.back()">取消</el-button>
					</el-form-item>
				</el-form>
				</div>
				<!-- 点击获取位置 -->
				<MapContainer  ref="map" :def-marker="form.lnglat" :icon="iconType" @callback="mapCb"/>

			</div>
		</el-card>
	</div>
</template>

<script>
	import uploadImage from '@/components/uploadImage'
	// import regions from 'ele-admin/packages/regions'
	import organizationSelect from '@/components/organizationSelect'
	import exceptionCategorySelect from '@/components/exceptionCategorySelect'
	import operationCategorySelect from '@/components/operationCategorySelect'
	import MapContainer from '@/components/Map/MapContainer'
  //import StreetSelect from "@/components/streetSelect.vue";
  import { regionData } from 'element-china-area-data'
	
	export default {
		name: 'emergencyEdit',
		components: {
      //StreetSelect,
			uploadImage,
			organizationSelect,
			exceptionCategorySelect,
			operationCategorySelect,
			MapContainer
	},
	computed: {
		iconType() {
			console.log("111", this.form.operation_category,(Number(this.form.operation_category)).toString())
			if (this.form.operation_category) {
				return (this.form.operation_category).toString()
			} else{ 
				return ''
			}
		}
	},
		data() {
			return {
				regions: regionData,
				loading: false,
				saveLoading: false,
				id: 0,
				form: {
					id: 0,
          operation_no: '',
          organization_id: null,
          operation_category: null,
          exception_category: null,
          area_id: [],
          province:'12',
          city:'12',
          county:'12',
          street:'12',
          address: '',
          organization_show: 1,
          penalty: 0,
          description: '',
          images: [],
          latitude:'',
          longitude:'',
					log_id:'',
					lnglat:[],
          street_id:''
				},
				rules: {
					operation_category: [
						{ required: true, message: '请选择作业类别', trigger: ['change','blur'] }
					],
					organization_id: [
						{ required: true, message: '请选择上报单位', trigger: ['change','blur'] }
					],
					exception_category: [
						{ required: true, message: '请选择巡查分类', trigger: ['change','blur'] }
					],
					address: [
						{ required: true, message: '请选择打标地址', trigger: ['change','blur'] }
					]
				},
				list:[]
			}
		},
		beforeRouteEnter(to, from, next) {
			next((vm) => {
				vm.info(to.query.id)
			})
		},
		beforeRouteLeave(to, from, next) {
			this.form = {
				id: 0,
          operation_no: '',
          organization_id: null,
          operation_category: null,
          exception_category: null,
          area_id: [],
          province:'12',
          city:'12',
          county:'12',
          street:'12',
          address: '',
          organization_show: 1,
          penalty: 0,
          description: '',
          images: [],
          latitude:'',
          longitude:'',
					log_id:'',
					lnglat:[]
			}
			this.$refs['form'].resetFields()
			next()
		},
		created(){},
		methods: {
			// 点击地图回调
			mapCb(data) {
				console.log('点击地图回调', data)

				this.form.area_id = this.get(data.adcode)
				this.form.address = data.address
        this.form.longitude = data.lnglat[0]
        this.form.latitude = data.lnglat[1]
			},
			changeArea(val) {
				this.form.address = ''
				const getLabel = function (val, arr, index = 0, res = []) {
					for (let i in arr) {
						if (arr[i].value === val[index]) {
							res.push(arr[i].label)
							if (index === val.length - 1) {
								return res
							} else {
								return getLabel(val, arr[i].children, ++index, res)
							}
						}
					}
				}
				let city = getLabel(val, this.regions)
				this.$refs.map.setCenterByLocation(city.join())
			},
			// 根据区域id获取 省市区id
			get(value, arr = this.regions) {
				for (const obj of arr) {
					if (obj.value === value) {
						return [obj.value, ...this.get(value, obj.children || [])]
					}

					if (obj.children) {
						const res = this.get(value, obj.children)

						if (res.length) {
							return [obj.value, ...res]
						}
					}
				}

				return []
			},
			async getOperationNo() {
				this.$http.post('/emergency/getOperationNo').then(res => {
					this.form.operation_no=res.data.data
				})
			},
			getList() {
				this.$http
						.post('/emergency/getLog', {operation_no:this.form.operation_no})
						.then((res) => {
							if (res.data.code === 0) {
								for (let i in res.data.data) {
									this.list.push({
										...res.data.data[i],
										operation_category_name:(res.data.data[i].operation_category == 1 ?'异常':res.data.data[i].operation_category == 2 ?'正常':'已处罚'),
										images:res.data.data[i].images_arr,
										lnglats: [Number(res.data.data[i].longitude), Number(res.data.data[i].latitude)]
									})
								}
							} else {
								this.$message.error(res.data.msg)
							}
						})
						.catch((e) => {
							this.$message.error(e.message)
						})
			},
			info(id) {
				if (!id) {
          this.getOperationNo()
					return
				}
				this.loading = true
				this.$http
					.post('/emergency/info', { id: id })
					.then((res) => {
						this.loading = false
						if (res.data.code === 0) {
							this.form = res.data.data
									if(this.form.longitude&&this.form.latitude){
										this.form.lnglat = [this.form.longitude||'', this.form.latitude||'']
										this.$refs.map.setMarker(this.form.lnglat)
									}else{
										// this.$refs.map.setCenterByLocation(this.regions.getLabel(this.form.area_id))
									}
							} else {
							this.$message.error(res.data.msg)
						}
					})
					.catch((e) => {
						this.loading = false
						this.$message.error(e.message)
					})
			},
			save() {
				this.$refs['form'].validate((valid) => {
					if (valid) {
						this.saveLoading = true
						this.$http
							.post('/emergency/edit', this.form)
							.then((res) => {
								this.saveLoading = false
								if (res.data.code === 0) {
									this.$message({ type: 'success', message: res.data.msg })
									// if(this.form.id){
									// 	this.getList()
									// }else{
									// 	this.$router.push('/road-traffie/emergency/index')
									// }
									this.getList()
								} else {
									this.$message.error(res.data.msg)
								}
							})
							.catch((e) => {
								this.saveLoading = false
								this.$message.error(e.message)
							})
					} else {
						return false
					}
				})
			},
      goHistory(){
        this.$router.push({
          path: '/road-traffie/emergency/history',
          query: { address_detailed:this.form.address,operation_no:this.form.operation_no }
        })
      }
		}
	}
</script>

<style scoped>
	._card {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	._form {
		width: 400px;
	}
  .form-title{
    padding-left: 20px;
    height: 36px;
    background: linear-gradient(90deg, #0758C4 0%, rgba(7,88,196,0) 100%);
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    line-height: 36px;
    font-size: 16px;
    font-weight: 500;
    color: #FFFFFF;
    margin-bottom: 15px;
  }
.logDiv{
  margin-left: 100px;
  line-height: 36px;
  border: 1px solid #c0c4cc;
  margin-bottom: 10px;
  text-align: center;
  cursor: pointer;
}
</style>
